<template>
  <!-- 对话框表单 -->
  <el-dialog class="ba-operate-dialog"
             :close-on-click-modal="false"
             :model-value="['batchSendMess'].includes(baTable.form.operate!)"
             @close="baTable.toggleForm"
             :destroy-on-close="true"
             title="消息群发">
    <el-scrollbar v-loading="loading"
                  class="ba-table-form-scrollbar">
      <div class="ba-operate-form"
           :class="'ba-' + baTable.form.operate + '-form'"
           :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'">
        <el-form ref="formRef"
                 :label-position="config.layout.shrink ? 'top' : 'right'"
                 :label-width="baTable.form.labelWidth + 'px'"
                 v-if="!baTable.form.loading">
          <FormItem label="群发消息"
                    v-model="text"
                    type="textarea"
                    :input-attr="{
                          rows: 20,
                    }"
                    prop="text"
                    :placeholder="t('Please input field', { field: '群发消息' })" />
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <el-button @click="baTable.toggleForm('')">{{ t('Cancel') }}</el-button>
      <el-button type="primary"
                 :loading="loading"
                 @click="onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
  
<script setup lang="ts">
import { ref, inject, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import { ElMessage, type FormInstance } from 'element-plus'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import { batchSendMess } from '/@/api/backend/customer/privateMessage'
const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass
const loading = ref(false)
const { t } = useI18n()
const text = ref('')
const onSubmit = () => {
    const ids = baTable.getSelectionIds()
    if(!text.value) {
        ElMessage ({
            type: 'warning',
            message: '不能发送空内容',
        })
        return
    }
    loading.value = true
    batchSendMess({ids, content: text.value}).then((res:any) => {
        if(res.code == 200) {
            ElMessage ({
                type: 'success',
                message: res.msg,
            })
            baTable.toggleForm('')
            baTable.onTableHeaderAction('refresh', {})
        } else {
            ElMessage ({
                type: 'error',
                message: res.msg,
            })
        }
    }).finally(() => {
        loading.value = false
    })
}

watch(
    () => baTable.form.operate,
    (val) => {
        if(val == 'batchSendMess') {
            text.value = ''
        }
    }
)
</script>